package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dao.DishDao;
import com.itheima.dao.DishFlavorDao;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishDto;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    DishService dishService;

    @Autowired
    DishDao dishDao;

    @Autowired
    DishFlavorDao dishFlavorDao;

    @Autowired
    RedisTemplate redisTemplate;

    //分页查询+条件查询
    @GetMapping("/page")
    //参数以k:v格式转发，不用加注解
    public R<Map> SelectPage(Integer page, Integer pageSize, String name) {
        Page<Dish> employeePage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(name != null, Dish::getName, name).orderByDesc(Dish::getUpdateTime);
        Page<Dish> pageInfo = dishService.page(employeePage, wrapper);
        //总条数,Long类型会转为string类型，前端页面不显示
        Integer total = Math.toIntExact(pageInfo.getTotal());
        //查询列表数据
        List<Dish> records = pageInfo.getRecords();
        Map map = new HashMap();
        map.put("total", total);

        // records: List<Dish>
        // 只：category有菜品分类idId，没有分类名称
        // 根据菜品分类id，查询菜品分类数据。在set进去
        ArrayList<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : records) {
            //获取菜品分类id
            Long categoryId = dish.getCategoryId();
            //根据分类id去查询菜品分类
            Category category = categoryService.getById(categoryId);
            //通过获取的菜品分类对象去获取该菜品分类的名称
            String categoryName = category.getName();
            DishDto dishDto = new DishDto();
            //将分类名称赋值
            dishDto.setCategoryName(categoryName);
            // 还需要将Dish dish 数据放入到 DishDto dishDto 里面
            BeanUtils.copyProperties(dish, dishDto);
            //添加到dishDtos集合中
            dishDtoList.add(dishDto);
        }
        //将带有分类名称的数据集合添加到map中
        map.put("records", dishDtoList);
        return R.success(map);
    }

    //删除菜品
    @DeleteMapping
    public R<String> deleteById(@RequestParam List<Long> ids) {
      /*  //逻辑删除菜品
        dishService.removeByIds(ids);
        //逻辑删除菜品的口味
        for (Long DishId : ids) {
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId,DishId);
            dishFlavorDao.delete(wrapper);
        }
*/
        String s = dishService.deleteById(ids);
        return R.success(s);

    }

    //添加菜品
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto) {
        //1.清理当前分类下面的菜品缓存数据
//        redisTemplate.delete("dish_" + dishDto.getCategoryId());
        //2.清理所有分类下的菜品缓存
        Set keys = redisTemplate.keys("dish*");
        redisTemplate.delete(keys);
        //保存菜品数据
        dishService.save(dishDto);
        //获取DishFlavor数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        //判断用户是否添加了口味
        if (flavors != null && flavors.size() > 0) {
            //遍历集合中的DishFlavor对象
            //保存菜品的口味数据 需要注意：DishFlavor中dishId是没有数据的，
            // 所以需要手动设置
            Long dishId = dishDto.getId();//获取菜品id
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
                dishFlavorDao.insert(flavor);
            }
        }
        return R.success("添加成功");
    }

    //根据菜品Id回显修改的菜品数据
    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id) {
        DishDto dishDto = new DishDto();
        Dish dish = dishService.getById(id);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        //根据dishId查DishFlavor表
        wrapper.eq(DishFlavor::getDishId, id);
        //查出与菜品关联的口味的数据集合
        List<DishFlavor> dishFlavors = dishFlavorDao.selectList(wrapper);
        //dishDto中的Flavor属性赋值，是个集合
        dishDto.setFlavors(dishFlavors);
        //将dish菜品表中数据拷贝到dishDto中相同属性
        BeanUtils.copyProperties(dish, dishDto);
        return R.success(dishDto);
    }

    //修改菜品
    @PutMapping
    public R updateDish(@RequestBody DishDto dishDto){
        //1.清理当前分类下面的菜品缓存数据
        redisTemplate.delete("dish_" + dishDto.getCategoryId());
        //2.清理所有分类下的菜品缓存
//        Set keys = redisTemplate.keys("dish*");
//        redisTemplate.delete(keys);
        Dish dish = new Dish();
        //获取dishId
        Long id = dishDto.getId();
        //将dishDto数据拷贝到dish中相同的属性中
        BeanUtils.copyProperties(dishDto,dish);
        //更新dish表中的数据
        dishService.updateById(dish);
        //delete from dishFlavor where dishId = ？  删除所有的口味
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,id);
        dishFlavorDao.delete(wrapper);
        //获取修改后的口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历加入表中
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
            dishFlavorDao.insert(flavor);
        }
        return R.success("修改成功");
    }

    //起售/停售 批量起售/批量停售

    @PostMapping("/status/{status}")
    public R updateStatus(@RequestParam List<Long> ids,@PathVariable Integer status){
        //update dish set status = {id} where id in(1,2,3);
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Dish::getStatus,status).in(Dish::getId,ids);

//
//        for (Long id : ids) {
//            Dish dish = new Dish();
//            dish.setStatus(status);
//            dish.setId(id);
//            dishService.updateById(dish);
//        }

        dishService.update(wrapper);
        return R.success("操作成功");
    }

//    根据分类id查询该分类下的所有菜品集合
    //前台菜品展示页面口味也要传过去
    @GetMapping("/list")
    public R<List<DishDto>> selectCategoryById(Long categoryId){
        //动态构造key
        String key = "dish_" + categoryId;
        //获取redis中缓存的数据
        List<DishDto> dishList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //判断redis是否有缓存数据，有直接将数据传给前端
        if(dishList != null){
            return R.success(dishList);
        }
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,categoryId);
        List<Dish> list = dishService.list(wrapper);
        ArrayList<DishDto> dishDtos = new ArrayList<>();    //dish+dishFlavor的集合
        for (Dish dish : list) {    //遍历菜品集合
            Long dishId = dish.getId(); //获取每个菜品的id
            //select * from dish_flavor where dishId = ?
            LambdaQueryWrapper<DishFlavor> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> flavors = dishFlavorDao.selectList(wrapper2);  //获取遍历菜品的口味
            DishDto dishDto = new DishDto();    //dishDto对象
            dishDto.setFlavors(flavors);    //将口味赋值给dishDto对象
            BeanUtils.copyProperties(dish,dishDto); //将dish中的数据copy给dishDto中
            dishDtos.add(dishDto);  //添加到dishDto集合中
        }
        redisTemplate.opsForValue().set(key,dishDtos);
        return R.success(dishDtos);     //将完整数据返回
    }

}
